package com.yx.front.converter;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.yx.front.enums.Sex;
import com.yx.front.enums.TimeFormat;
import com.yx.front.manager.DictManager;
import com.yx.front.model.SysUser;
import com.yx.front.model.param.SysUserParam;
import com.yx.front.model.vo.SysUserVo;
import com.yx.front.utils.LoginUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author YangXiong
 */
@Component
public class SysUserConverter {
    @Resource
    private LoginUtil loginUtil;
    @Resource
    private DictManager dictManager;
    @Resource
    private PasswordEncoder bCryptPasswordEncoder;

    public SysUser getSysUser(SysUserParam param) {
        SysUser sysUser = new SysUser();
        String pwd = bCryptPasswordEncoder.encode(param.getPassword());
        sysUser.setId(null);
        sysUser.setPassword(pwd);
        sysUser.setAccount(param.getAccount());
        sysUser.setUserName(param.getUserName());
        sysUser.setCreateTime(DateUtil.date());
        sysUser.setUpdateTime(DateUtil.date());
        DateTime lastLoginTime = DateUtil.parse(param.getLastLoginTime());
        sysUser.setLastLoginTime(lastLoginTime);
        setUpdateUser(sysUser);
        sysUser.setUpdateTime(DateUtil.date());
        return sysUser;
    }

    private void setUpdateUser(SysUser sysUser) {
        SysUser currentUser = loginUtil.getCurrentUser();
        if (Objects.nonNull(currentUser)) {
            sysUser.setUserName(currentUser.getUserName());
        }
    }

    public SysUserVo sysUserToVo(SysUser one) {
        SysUserVo vo = new SysUserVo();
        if (Objects.nonNull(one)) {
            vo.setId(one.getId());
            vo.setAvatar(one.getAvatar());
            vo.setAccount(one.getAccount());
            vo.setUserName(one.getUserName());
            vo.setBirthday(DateUtil.format(one.getBirthday(), TimeFormat.DATE_FORMAT));
            vo.setEmail(one.getEmail());
            vo.setPhone(one.getPhone());
            vo.setHobby(dictManager.getTextByValue(one.getHobby()));
            vo.setSex(Sex.getValueByKey(one.getSex()));
        }
        return vo;
    }
}
